/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.hpvas.persistence.dao;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import edu.hpvas.persistence.entity.MedicalRecord;
import edu.hpvas.persistence.entity.Owner;
import edu.hpvas.persistence.entity.Pet;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author raider
 */
public class PetDAO implements Serializable {

    public PetDAO() {
        this.emf = Persistence.createEntityManagerFactory("HPVAS");
    }
    private EntityManagerFactory emf;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Pet pet) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            /*
            MedicalRecord idMedicalRecord = pet.getIdMedicalRecord();
            if (idMedicalRecord != null) {
                idMedicalRecord = em.getReference(idMedicalRecord.getClass(), idMedicalRecord.getId());
                pet.setIdMedicalRecord(idMedicalRecord);
            }
            Owner idOwner = pet.getIdOwner();
            if (idOwner != null) {
                idOwner = em.getReference(idOwner.getClass(), idOwner.getId());
                pet.setIdOwner(idOwner);
            }
            em.persist(pet);
            if (idMedicalRecord != null) {
                idMedicalRecord.getPetCollection().add(pet);
                idMedicalRecord = em.merge(idMedicalRecord);
            }
            if (idOwner != null) {
                idOwner.getPetCollection().add(pet);
                idOwner = em.merge(idOwner);
            }*/
            em.persist(pet);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPet(pet.getId()) != null) {
                System.out.println("Pet " + pet + " already exists.");
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Pet pet,Pet newPet) throws Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            pet = findPet(pet.getId());
            pet.setAge(newPet.getAge());
            pet.setName(newPet.getName());
            pet.setSpecies(newPet.getSpecies());
            pet.setWight(newPet.getWight());
            em.merge(pet);
            /*MedicalRecord idMedicalRecordOld = persistentPet.getIdMedicalRecord();
            MedicalRecord idMedicalRecordNew = pet.getIdMedicalRecord();
            Owner idOwnerOld = persistentPet.getIdOwner();
            Owner idOwnerNew = pet.getIdOwner();
            if (idMedicalRecordNew != null) {
                idMedicalRecordNew = em.getReference(idMedicalRecordNew.getClass(), idMedicalRecordNew.getId());
                pet.setIdMedicalRecord(idMedicalRecordNew);
            }
            if (idOwnerNew != null) {
                idOwnerNew = em.getReference(idOwnerNew.getClass(), idOwnerNew.getId());
                pet.setIdOwner(idOwnerNew);
            }
            pet = em.merge(pet);
            if (idMedicalRecordOld != null && !idMedicalRecordOld.equals(idMedicalRecordNew)) {
                idMedicalRecordOld.getPetCollection().remove(pet);
                idMedicalRecordOld = em.merge(idMedicalRecordOld);
            }
            if (idMedicalRecordNew != null && !idMedicalRecordNew.equals(idMedicalRecordOld)) {
                idMedicalRecordNew.getPetCollection().add(pet);
                idMedicalRecordNew = em.merge(idMedicalRecordNew);
            }
            if (idOwnerOld != null && !idOwnerOld.equals(idOwnerNew)) {
                idOwnerOld.getPetCollection().remove(pet);
                idOwnerOld = em.merge(idOwnerOld);
            }
            if (idOwnerNew != null && !idOwnerNew.equals(idOwnerOld)) {
                idOwnerNew.getPetCollection().add(pet);
                idOwnerNew = em.merge(idOwnerNew);
            }*/
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = pet.getId();
                if (findPet(id) == null) {
                    System.out.println("The pet with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Pet pet = null;
            try {
                pet = em.getReference(Pet.class, id);
                pet.getId();
            } catch (EntityNotFoundException enfe) {
                System.out.println("The pet with id " + id + " no longer exists.");
            }
            MedicalRecord idMedicalRecord = pet.getIdMedicalRecord();
            if (idMedicalRecord != null) {
                idMedicalRecord.getPetCollection().remove(pet);
                idMedicalRecord = em.merge(idMedicalRecord);
            }
            Owner idOwner = pet.getIdOwner();
            if (idOwner != null) {
                idOwner.getPetCollection().remove(pet);
                idOwner = em.merge(idOwner);
            }
            em.remove(pet);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Pet> findPetEntities() {
        return findPetEntities(true, -1, -1);
    }

    public List<Pet> findPetEntities(int maxResults, int firstResult) {
        return findPetEntities(false, maxResults, firstResult);
    }

    private List<Pet> findPetEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Pet.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
            
        }catch(NullPointerException n){
            return new ArrayList<>();
        }
        finally {
            em.close();
        }
    }

    public Pet findPet(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Pet.class, id);
        } finally {
            em.close();
        }
    }
    
    public Pet findPetEntitiesByName(String name){
        EntityManager em=getEntityManager();
        Query query= em.createQuery("select p from Pet p where p.name=:name").setParameter("name", name);
        if(!query.getResultList().isEmpty()) {
            return (Pet) query.getSingleResult();
        }
        else {
            return null;
        }
    }
    public List<Pet> findPetsEntitiesByName(String name){
        EntityManager em=getEntityManager();
        Query query= em.createQuery("select p from Pet p where p.name=:name").setParameter("name", name);
        if(!query.getResultList().isEmpty()) {
            return query.getResultList();
        }
        else {
            return null;
        }
    }

    public int getPetCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Pet> rt = cq.from(Pet.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
